/*
 * 上海远境文化传媒有限公司 版权所有
 */
package ext.map;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import helper.GlobalConfig;
import helper.GsonHelper;
import helper.UrlHelper;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import play.Logger;
import play.libs.WS;

import java.math.BigDecimal;

/**
 * 高德地图封装.
 */
public class AMapHelper {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AMapHelper.class);

    /**
     * 从地址得到GEO信息.
     */
    public static AddressData geocode(String address) {
        String url = "https://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + GlobalConfig.AMAP_WEBAPI_KEY;
        logger.info("TLQ251760: url={}", url);
        WS.HttpResponse response = WS.url(url).get();
        JsonElement resultJsonElement = response.getJson();
        Logger.info("resultJsonElement :" + resultJsonElement);
        JsonObject resultJsonObject = resultJsonElement.getAsJsonObject();

        String status = GsonHelper.getString(resultJsonObject, "status");

        if (!"1".equals(status)) {
            logger.info("TLQ270640: 调用高德接口失败，address=" + address);
            return null;
        }

        AddressData addressData = getAddressDataFromJson(address, resultJsonObject);
        return addressData;
    }

    /**
     * 从地址得到GEO信息.
     */
    public static AddressData geocode(String address, String city) {
        if (StringUtils.isBlank(city)) {
            return geocode(address);
        }

        String url = "https://restapi.amap.com/v3/geocode/geo?address=" + address + "&city=" + city + "&output=JSON&key=" + GlobalConfig.AMAP_WEBAPI_KEY;
        logger.info("TLQ251761: url={}", url);
        WS.HttpResponse response = WS.url(url).get();
        JsonElement resultJsonElement = response.getJson();
        Logger.info("resultJsonElement :" + resultJsonElement);
        JsonObject resultJsonObject = resultJsonElement.getAsJsonObject();

        String status = GsonHelper.getString(resultJsonObject, "status");

        if (!"1".equals(status)) {
            logger.info("TLQ270641: 调用高德接口失败，address=" + address);
            return null;
        }

        AddressData addressData = getAddressDataFromJson(address, resultJsonObject);
        return addressData;
    }

    private static AddressData getAddressDataFromJson(String address, JsonObject resultJsonObject) {
        JsonArray jsonArray = resultJsonObject.get("geocodes").getAsJsonArray();

        if (jsonArray.size() == 0) {
            return new AddressData();
        }

        JsonObject geocodesJsonObject = jsonArray.get(0).getAsJsonObject();
        AddressData addressData = new AddressData();
        addressData.country = "中国";
        addressData.address = address;
        addressData.formattedAddress = GsonHelper.getString(geocodesJsonObject, "formatted_address");
        addressData.province = GsonHelper.getString(geocodesJsonObject, "province");
        addressData.city = GsonHelper.getString(geocodesJsonObject, "city");
        addressData.district = GsonHelper.getString(geocodesJsonObject, "district");
        addressData.cityCode = GsonHelper.getString(geocodesJsonObject, "citycode");
        // postCode应该不会对
        addressData.postCode = GsonHelper.getString(geocodesJsonObject, "adcode");
        addressData.adcode = GsonHelper.getString(geocodesJsonObject, "adcode");

        String location = GsonHelper.getString(geocodesJsonObject, "location");
        String[] locationArray = StringUtil.split(location, ",");
        if (locationArray.length == 2) {
            addressData.longitude = new BigDecimal(locationArray[0]);
            addressData.latitude = new BigDecimal(locationArray[1]);
        }
        return addressData;
    }

    /**
     * 静态地图显示
     *
     * @param latitude
     * @param longitude
     * @param size      750*300
     */
    public static String staticMap(BigDecimal longitude, BigDecimal latitude, String size) {
        return UrlHelper.getHttpPrefix() + "restapi.amap.com/v3/staticmap?location="
                + longitude + "," + latitude
                + "&zoom=10&size=" + size + "&markers=mid,0xFF0000,A:" + longitude + "," + latitude + "&key=" + GlobalConfig.AMAP_WEBAPI_KEY;
    }

    public static WeatherData weatcher(String adCode) {
        String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=" + adCode+ "&extensions=base&output=JSON&key=" + GlobalConfig.AMAP_WEBAPI_KEY;
        logger.info("TLQ251711: url={}", url);
        WS.HttpResponse response = WS.url(url).get();
        JsonElement resultJsonElement = response.getJson();
        Logger.info("TLQ251712: resultJsonElement :" + resultJsonElement);
        JsonObject resultJsonObject = resultJsonElement.getAsJsonObject();

        String status = GsonHelper.getString(resultJsonObject, "status");

        if (!"1".equals(status)) {
            logger.info("TLQ270631: 调用高德weatherInfo接口失败，city=" + adCode);
            return null;
        }

        WeatherData weatherData = new WeatherData();

        JsonArray jsonArray = resultJsonObject.get("lives").getAsJsonArray();

        if (jsonArray.size() == 0) {
            return weatherData;
        }


        JsonObject livesJson = jsonArray.get(0).getAsJsonObject();
        weatherData.province = GsonHelper.getString(livesJson, "province");
        weatherData.city = GsonHelper.getString(livesJson, "city");
        weatherData.adcode = GsonHelper.getString(livesJson, "adcode");
        weatherData.reportTime = GsonHelper.getString(livesJson, "reporttime");
        weatherData.humidity = GsonHelper.getString(livesJson, "humidity");
        weatherData.windPower = GsonHelper.getString(livesJson, "windpower");
        weatherData.windDirection = GsonHelper.getString(livesJson, "winddirection");
        weatherData.temperature = GsonHelper.getString(livesJson, "temperature");
        weatherData.weather = GsonHelper.getString(livesJson, "weather");

        return weatherData;
    }
}
